<template>
  <el-table
    ref="tableRef"
    v-loading="listLoading"
    border
    :data="list"
    row-key="id"
    :tree-props="{ children: 'children', hasChildren: hasChildren }"
    @selection-change="setSelectRows"
  >
    <el-table-column v-if="show_selection" type="selection" width="38" />
    <el-table-column v-if="show_id && hasChildren != 'hasChildren'" align="center" label="序号" width="55">
      <template #default="{ row }">
        <div @click="clickField(row.id, 'id', row.id)">{{ row.id }}</div>
      </template>
    </el-table-column>

    <template v-if="config_table.cols">
      <template v-for="(show_item, show_index) in config_table.list_show" :key="show_index">
        <template v-for="(col, index) in config_table.cols" :key="index">
          <template
            v-if="
              show_item == col.field &&
              show_item != 'id' &&
              show_item != 'uniacid' &&
              show_item != 'is_del' &&
              !col.password &&
              !col.textarea
            "
          >
            <template v-if="show_item == 'status'">
              <el-table-column align="center" label="状态" show-overflow-tooltip>
                <template #default="{ row }">
                  <el-tooltip class="item" :content="row.show_status" :effect="'dark'" placement="top-start">
                    <el-tag
                      v-if="row.id"
                      :effect="light ? '' : 'dark'"
                      :type="statusFilter(row.show_status)"
                      @click="clickField(row.id, show_item, row.status)"
                    >
                      {{ row.show_status }}
                    </el-tag>
                    <span v-else>{{ row.show_status }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>
            </template>
            <template v-else>
              <template v-if="col.model">
                <el-table-column align="center" :label="col.comment" show-overflow-tooltip>
                  <template #default="{ row }">
                    <el-tooltip
                      v-if="row && row[col.model] && row[col.model][col.show_field]"
                      class="item"
                      :content="row[col.model][col.show_field]"
                      :effect="'dark'"
                      placement="top-start"
                    >
                      <el-tag
                        v-if="row[col.model][col.show_field] && row.id"
                        :effect="light ? '' : 'dark'"
                        :type="statusFilter(row.show_status)"
                        @click="clickField(row.id, show_item, row[col.field])"
                      >
                        {{ row[col.model][col.show_field] }}
                      </el-tag>
                      <span v-else>{{ row[col.model][col.show_field] }}</span>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </template>
              <template v-else>
                <template v-if="col.img">
                  <el-table-column align="center" :label="col.comment" show-overflow-tooltip>
                    <template #default="{ row }">
                      <!-- <el-image v-if="row[col.field].length > 0 && row[col.field][0].url" :src="row[col.field][0].url" /> -->
                      <!-- 点击花屏错误 -->
                      <el-image
                        v-if="row[col.field].length > 0 && row[col.field][0].url"
                        :preview-src-list="row[col.field + '_url']"
                        :preview-teleported="true"
                        :src="row[col.field][0].url"
                      />
                    </template>
                  </el-table-column>
                </template>
                <template v-else>
                  <el-table-column align="center" :label="col.comment" show-overflow-tooltip>
                    <template #default="{ row }">
                      <div @click="clickField(row.id, show_item, row[col.field], row)">{{ row[col.field] }}</div>
                    </template>
                  </el-table-column>
                </template>
              </template>
            </template>
          </template>
        </template>
      </template>
    </template>

    <el-table-column
      v-if="detail_path != '' || config_table._edit == '1' || config_table._del == '1'"
      align="center"
      label="操作"
      min-width="150px"
      :width="detail_path != '' ? '230px' : '180px'"
    >
      <template #default="{ row }">
        <el-button v-if="!is_recycle && detail_path != '' && row.id" text type="success" @click="detail(row)">详情</el-button>
        <el-button v-if="is_copy && !is_recycle && row.id" text type="primary" @click="copy(row)">复制</el-button>
        <el-button v-if="!is_recycle && config_table._edit == '1' && row.id" text type="primary" @click="edit(row)">编辑</el-button>
        <el-button v-if="!is_recycle && config_table._del == '1' && row.id" text type="danger" @click="del(row)">删除</el-button>

        <el-button v-if="is_recycle && row.id" text type="primary" @click="recovery(row)">恢复</el-button>
        <!-- <el-button v-if="is_recycle && row.id" text type="danger" @click="com_del(row)">彻底删除</el-button> -->
      </template>
    </el-table-column>
    <template #empty>
      <el-empty class="vab-data-empty" description="暂无数据" />
    </template>
  </el-table>
</template>

<script lang="ts" setup>
//el-image图片预览组件在el-table表格中预览部分被遮盖，z-index不够，请添加preview-teleported属性
// # 使用 npm 的情况，安装最新版本
// npm install element-plus@latest
import {
  api_com_del,
  api_com_delChecked,
  api_del,
  api_delChecked,
  api_detail,
  api_recovery,
  api_recoveryChecked,
  api_exportsChecked,
  api_exports,
} from '/@/api/obj'

defineOptions({
  name: 'ObjTableBase',
})
const props = defineProps({
  is_copy: {
    type: Boolean,
    default: false,
  },
  detail_path: {
    type: String,
    default: '',
  },
  detail_column: {
    type: Number,
    default: 2,
  },
  detail_hide: {
    type: String,
    default: '',
  },
  detail_st: {
    type: String,
    default: '',
  },
  detail_son_id: {
    type: String,
    default: '',
  },
  show_id: {
    type: Boolean,
    default: true,
  },
  is_recycle: {
    type: Boolean,
    default: false,
  },
  config_table: {
    type: Object,
    default: {},
  },
  list: {
    type: Array,
    default: [],
  },
  listLoading: {
    type: Boolean,
    default: false,
  },
  statusMap: {
    type: Object,
    default: {},
  },
  light: {
    type: Boolean,
    default: true,
  },
  show_selection: {
    type: Boolean,
    default: true,
  },
  hasChildren: {
    type: String,
    default: '',
  },
})
const tableRef = ref<any>(null)
const $baseConfirm = inject<any>('$baseConfirm')
const $baseMessage = inject<any>('$baseMessage')
const router = useRouter()
const emit = defineEmits(['getData', 'edit', 'copy', 'detail', 'clickField'])
//自定义颜色字段
const statusFilter = (status: string | number) => {
  const statusMap: any = props.statusMap
  return statusMap[status]
}

const selectRows = ref<any>([])
//通用详情
const detail = (row: any) => {
  const param = {
    t: props.config_table.tablename,
    id: row.id,
    column: props.detail_column,
    hide_field: props.detail_hide,
    showid: props.show_id ? 1 : 0,
    st: props.detail_st,
    son_id: props.detail_son_id,
  }
  router.push({
    path: props.detail_path,
    query: {
      ...param,
      timestamp: new Date().getTime(), //允许同一个详情页同时打开多次，否则会触发路由被缓存下次无法刷新的bug
    },
  })

  api_detail(props.config_table.tablename, { id: row.id }).then((res: any) => {
    console.log(res)
  })
}
//通用点击状态
const clickField = (id: any, field: any, value: any, row: any) => {
  emit('clickField', id, field, value, row)
}
//通用编辑
const edit = (row = {}) => {
  api_detail(props.config_table.tablename, { id: row.id }).then((res: any) => {
    console.log(res)
    //editRef.value.showEdit(res)
    emit('edit', res)
  })
}
const copy = (row = {}) => {
  api_detail(props.config_table.tablename, { id: row.id }).then((res: any) => {
    console.log(res)
    //editRef.value.showEdit(res)
    emit('copy', res)
  })
}

const exports = (row: any) => {
  console.log(props)
  if (row.id) {
    $baseConfirm('您确定要导出当前项吗', null, async () => {
      const { msg }: any = await api_exports(props.config_table.tablename, { id: row.id })
      $baseMessage(msg, 'success', 'hey')
      // await getData()
      emit('getData')
    })
  } else {
    if (selectRows.value.length > 0) {
      const ids = selectRows.value.map((item: { id: any }) => item.id).join()
      $baseConfirm('您确定要导出选中项吗', null, async () => {
        const { msg }: any = await api_exportsChecked(props.config_table.tablename, { ids: ids })
        console.log(msg)
        $baseMessage(msg, 'success', 'hey')
        emit('getData')
      })
    } else {
      $baseMessage('您未选中任何行', 'warning', 'hey')
    }
  }
}
//通用普通删除
const del = (row: any) => {
  console.log(props)
  if (row.id) {
    $baseConfirm('您确定要删除当前项吗', null, async () => {
      const { msg }: any = await api_del(props.config_table.tablename, { id: row.id })
      $baseMessage(msg, 'success', 'hey')
      // await getData()
      emit('getData')
    })
  } else {
    if (selectRows.value.length > 0) {
      const ids = selectRows.value.map((item: { id: any }) => item.id).join()
      $baseConfirm('您确定要删除选中项吗', null, async () => {
        const { msg }: any = await api_delChecked(props.config_table.tablename, { ids: ids })
        console.log(msg)
        $baseMessage(msg, 'success', 'hey')
        emit('getData')
      })
    } else {
      $baseMessage('您未选中任何行', 'warning', 'hey')
    }
  }
}
//通用彻底删除
const com_del = (row: any) => {
  if (row.id) {
    $baseConfirm('您确定要彻底删除当前项吗', null, async () => {
      const { msg }: any = await api_com_del(props.config_table.tablename, { id: row.id })
      $baseMessage(msg, 'success', 'hey')
      emit('getData')
    })
  } else {
    if (selectRows.value.length > 0) {
      const ids = selectRows.value.map((item: { id: any }) => item.id).join()
      $baseConfirm('您确定要删除选中项吗', null, async () => {
        const { msg }: any = await api_com_delChecked(props.config_table.tablename, { ids: ids })
        console.log(msg)
        $baseMessage(msg, 'success', 'hey')
        emit('getData')
      })
    } else {
      $baseMessage('您未选中任何行', 'warning', 'hey')
    }
  }
}
//通用恢复操作
const recovery = (row: any) => {
  if (row.id) {
    $baseConfirm('您确定要恢复当前项吗', null, async () => {
      const { msg }: any = await api_recovery(props.config_table.tablename, { id: row.id })
      $baseMessage(msg, 'success', 'hey')
      emit('getData')
    })
  } else {
    if (selectRows.value.length > 0) {
      const ids = selectRows.value.map((item: { id: any }) => item.id).join()
      $baseConfirm('您确定要恢复选中项吗', null, async () => {
        const { msg }: any = await api_recoveryChecked(props.config_table.tablename, { ids: ids })
        console.log(msg)
        $baseMessage(msg, 'success', 'hey')
        emit('getData')
      })
    } else {
      $baseMessage('您未选中任何行', 'warning', 'hey')
    }
  }
}

//通用设置选中行
const setSelectRows = (value: string) => {
  selectRows.value = value
}
defineExpose({
  del,
  recovery,
  com_del,
  selectRows,
  exports,
})
//通用选中
onActivated(() => {
  tableRef.value.doLayout()
})
</script>
<style scoped>
.z-col {
  width: 150px;
  padding: 5px;
}
</style>
